package com.nba.system.controller;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;














import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lowagie.text.*;
import com.lowagie.text.pdf.Barcode128;
import com.alibaba.fastjson.JSONObject;
import com.nba.common.utils.ResponseUtils;
import com.nba.common.controller.BaseController;
import com.nba.common.exception.CustomException;
import com.nba.common.form.RequestDataForm;
import com.nba.common.form.ResponseDataForm;
import com.nba.common.service.IService;
import com.nba.common.utils.DateUtil;
import com.nba.common.utils.Environment;
import com.nba.common.utils.FileUtils;
import com.nba.common.utils.MapUtils;
import com.nba.common.utils.PropertiesLoaderUtil;
import com.nba.common.web.httpobjects.MsgResult;

/**
 * @author Jesse 用户URL统一入口
 */
@Controller
@RequestMapping("/public")
public class PublicController extends BaseController{
	
	
	
	
	@RequestMapping(value = "/getFile/{id}")
	public void getFile(@PathVariable String id,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> urlSqlMap = jdbcDao.queryForMap(
				"select name, path, size, ext from accessory_file where id = ?",
				new Object[] { id });
		if (urlSqlMap == null || urlSqlMap.size() == 0) {
			throw new CustomException(-1,
					"附件不存在!.");
		}
		String basePath = PropertiesLoaderUtil.getPropValue("pic.base.path");
		String path = basePath + urlSqlMap.get("path").toString();
		String filename = urlSqlMap.get("name").toString();
		File file = new File(path);
        // 取得文件名。
        // 取得文件的后缀名。

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.setContentType("appliation/octet-stream"); 
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
            filename = URLEncoder.encode(filename, "UTF-8");  //针对IE
        } else {  
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  //针对IE之外的浏览器
        }
//     response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes(Environment.ENCODING), "ISO-8859-1"));
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
	}
	
	@RequestMapping(value = "/barcode/{id}")
	public void barcode(@PathVariable String id,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("=====");
        response.setHeader("connection", "close");
        response.setHeader("X-Powered-By", "Express");
		int barCodeWidth=180;  
		int barCodeHeight=20;  
		int HEIGHT_SPACE = 15;     
		          
		//图片宽度     
		int imageWidth = barCodeWidth;     
		// 图片高度     
		int imageHeight = barCodeHeight + HEIGHT_SPACE ;    
		          
		BufferedImage img = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB);  
		  
		Graphics2D g = (Graphics2D) img.getGraphics();   
		g.fillRect(0, 0, imageWidth, imageHeight);   
		  
		Font font = new Font();
		font.setSize(12);
		          
		Barcode128 barcode128 = new Barcode128();  
		          
		// 图片横坐标开始位置     
		int startX = 0;     
		// 图片纵坐标开始位置     
		int imageStartY = 0;     
		// 条形码（文字）开始位置
		int stringStartY = imageHeight-3;   
		          
		barcode128.setCode(id);  
		java.awt.Image codeImg = barcode128.createAwtImage(Color.black, Color.white);  
		
		g.drawImage(codeImg, startX, imageStartY, barCodeWidth, barCodeHeight, Color.white, null);  
		
		//为图片添加条形码（文字），位置为条形码图片的下部居中  
		AttributedString ats = new AttributedString(id);   
		ats.addAttribute(TextAttribute.FONT, font, 0, id.length());
		AttributedCharacterIterator iter = ats.getIterator();  
		  
		// 设置条形码（文字）的颜色    
		g.setColor(Color.BLACK);
		// 绘制条形码（文字）     
		g.drawString(iter, startX + 2, stringStartY);   
		g.dispose();   
		
		ImageIO.write(img, "JPEG", response.getOutputStream()); 
		
		response.getWriter().close();
	}
	
	
}
